package com.framewrok.core.poi.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ResourceUtil {
	private static final String SDF = "_yyyyMMdd_HHmmss";

	private static String generateName(String name) {
		String time = new SimpleDateFormat(SDF).format(new Date());
		if (name.contains(".")) {
			int site = name.lastIndexOf(".");
			return name.substring(0, site) + time + name.substring(site);
		}
		return name + time;
	}

	private static String generatePath() {
		File file = new File("/generate/");
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getAbsolutePath();
	}

	public static File generateFileByTmplate(File templateFile) {
		String templateName = templateFile.getName();
		String generateName = generateName(templateName);
		return new File(generatePath(), generateName);

	}

	public static File template(String name) {
		try {
			URL url = ResourceUtil.class.getResource("/" + name);
			URI uri = url.toURI();
			File file = new File(uri);
			return file;
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}

	public static String readReource(String name) {
		File file = template(name);
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		try {
			br = new BufferedReader(new FileReader(file));
			String tmp = null;
			while ((tmp = br.readLine()) != null) {
				sb.append(tmp + "\n");
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (Exception e) {

				}

		}
		return sb.toString();
	}

}
